﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
using Newtonsoft.Json.Linq;

namespace Test.Client.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        [AllowAnonymous]
        public ActionResult Index()
        {
            var token = User.Identity.GetAuthorizationToken();
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult GetJsonByService()
        {
            var token = User.Identity.GetAuthorizationToken();
            HttpClient webHttpClient = new HttpClient();
            webHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            webHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var reponse = webHttpClient.GetAsync("http://lhl.source.com/api/Values").Result;
           var tem= reponse.Content.ReadAsAsync<dynamic>().Result;

            return new JSONNetResult(tem);
        }
    }
    public class JSONNetResult : ActionResult
    {
        private readonly dynamic _data;
        public JSONNetResult(dynamic data)
        {
            _data = data;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = "application/json";
            response.Write(_data.ToString(Newtonsoft.Json.Formatting.None));
        }
    }



    public static class IdentityExtensions
    {
        /// <summary>
        /// 获取身份信息Token
        /// </summary>
        public static string GetAuthorizationToken(this IIdentity identity)
        {
            try
            {
                AuthenticationTicket ticket = new AuthenticationTicket(identity as ClaimsIdentity,
                    new AuthenticationProperties());
                var currentUtc = DateTime.UtcNow;
                ticket.Properties.IssuedUtc = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromHours(Startup.ExpiresTime));
                string token = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

                return token;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
    }
}